package com.example.online_forum.controller;

import com.example.online_forum.common.AppResult;
import com.example.online_forum.common.ResultCode;
import com.example.online_forum.config.AppConfig;
import com.example.online_forum.model.Article;
import com.example.online_forum.model.ArticleReply;
import com.example.online_forum.model.User;
import com.example.online_forum.services.IArticleReplyService;
import com.example.online_forum.services.IArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/reply")
@Api(tags = "回复接口")
public class ArticleReplyController {
    @Autowired
    IArticleService articleService;
    @Autowired
    IArticleReplyService articleReplyService;
    @PostMapping("/create")
    @ApiOperation("创建回复")
    public AppResult create(HttpServletRequest request, @ApiParam("帖子id") @RequestParam("articleId") @NonNull Long articleId,
                            @ApiParam("帖子内容") @RequestParam("content") @NonNull String content){

        //获取用户
        HttpSession session = request.getSession(false);
         User user = (User)session.getAttribute(AppConfig.USER_SESSION);
         if(user.getState() == 1){
             return AppResult.failed(ResultCode.FAILED_USER_BANNED);
         }
         //获取有回复的帖子对象
        Article article = articleService.selectById(articleId);
         if(article == null || article.getDeleteState() == 1){
             return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
         }
         if(article.getState() == 1){
             return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
         }
         //构建回复对象
        ArticleReply articleReply = new ArticleReply();
         articleReply.setArticleId(articleId);
         articleReply.setContent(content);
         articleReply.setPostUserId(user.getId());

         //调用dao层,写入回复信息
        articleReplyService.create(articleReply);
        return AppResult.success();
    }
    @ApiOperation("获取回复列表")
    @GetMapping("/getReplies")
    public AppResult<List<ArticleReply>> getRepliesByArticleId(@ApiParam("帖子id") @RequestParam("articleId") @NonNull Long articleId){
        //校验贴子是否存在
        Article article = articleService.selectById(articleId);
        if(article == null || article.getDeleteState() == 1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
        }
        List<ArticleReply> articleReplies = articleReplyService.selectByArticleId(articleId);
        //返回结果
        return AppResult.success(articleReplies);
    }
}
